#include "qNormativvnes.h"
#include <QItemSelectionModel>
#include <QSqlQuery>
#include <QMessageBox>
#include <QSqlRecord>
#include <QSqlError>
#include "chelperclass.h"
#include <QDesktopWidget>



QNormativVnes::QNormativVnes(QWidget *parent)
	: QMyBaseFormWidget(parent)
    , selRow(-1)
    , textId("")
    , proizvodID("")
    , artikal_id(0)
    , pItemDelegate(0)
    , editorOpen(0)
	, m_bProizvod(false)
{
    ui.setupUi(this);
	QDesktopWidget desk;
	QRect deskRect = desk.screenGeometry();
	ui.layoutWidget->setFixedWidth(deskRect.width() - 300);
	ui.layoutWidget->setFixedHeight(deskRect.height()-200);
    ui.lineEdit->setFocus();
    ui.lineEdit->setText("");
    ui.lineEdit->selectAll();
    ui.lineEdit_2->setText("");
	ui.lineEdit->setStyleSheet("background-color: yellow");
	ui.lineEdit->installEventFilter(this);
	ui.lineEdit_2->installEventFilter(this);
	ui.lineEdit_3->installEventFilter(this);
	ui.lineEdit_4->installEventFilter(this);
    ui.dateTimeEdit->installEventFilter(this);
    connect(ui.lineEdit, SIGNAL(returnPressed()), this, SLOT(on_pushButton_clicked()));
    connect(ui.lineEdit_2, SIGNAL(returnPressed()), this, SLOT(on_pushButton_2_clicked()));
    connect(ui.lineEdit_3, SIGNAL(returnPressed()), this, SLOT(on_plineEdit3_Pressed()));
    connect(ui.lineEdit_4, SIGNAL(returnPressed()), this, SLOT(on_plineEdit4_Pressed()));
    ui.dateTimeEdit->setDate(QDate::currentDate());
    pItemDelegate = new QSTableWidgetDelegate(ui.tableView);
    connect(this ,SIGNAL(editCell()),this,SLOT(openEditor()));
    connect(this ,SIGNAL(closeCell()),this,SLOT(closeEditor()));

    ui.tableView->setEditTriggers(QAbstractItemView::CurrentChanged);
    ui.tableView->setItemDelegate(pItemDelegate);

    model = new QStandardItemModel(0,5);
	model->setHeaderData( 0, Qt::Horizontal, trUtf8("Ид."));
	model->setHeaderData( 1, Qt::Horizontal, trUtf8("Шифра"));
	model->setHeaderData( 2, Qt::Horizontal, trUtf8("Артикал"));
	model->setHeaderData( 3, Qt::Horizontal, trUtf8("Едм."));
	model->setHeaderData( 4, Qt::Horizontal, trUtf8("Количина"));
// 	model->setHeaderData( 5, Qt::Horizontal, trUtf8("Цена"));

	ui.tableView->setSortingEnabled(true);
	connect(ui.tableView->horizontalHeader(),SIGNAL(sectionClicked(int)), ui.tableView, SLOT(sortByColumn(int)));

	ui.tableView->setModel(model);
    header = new QHeaderView(Qt::Horizontal, this);
    header->setClickable(true);
	ui.tableView->setHorizontalHeader(header);
    header->show();
}

QNormativVnes::~QNormativVnes()
{

}

void QNormativVnes::pressEscape()
{
	emit closeW();
}
void QNormativVnes::setKomintent(QString text, QString textName)
{
	ui.lineEdit->setText(textName);
    proizvodID = text;
}

void QNormativVnes::setFocusLine()
{
	ui.lineEdit->setFocus();
	ui.lineEdit->selectAll();
}

void QNormativVnes::setArtikli(QString text, QString textName)
{
	if (!m_bProizvod)
	{
		ui.lineEdit_2->setText(textName);
		textId = text;
		artikal_id = text.toInt();

		QSqlQuery query;
		query.prepare("select edm from artikli where id = :id");
		query.bindValue(":id", artikal_id);	
		query.exec();
		query.next();
		ui.lineEdit_3->setText(query.value(0).toString());
	}
	else
	{
        ui.lineEdit->setText(textName);
        artikal_id = text.toInt();

        QSqlQuery query;
        query.prepare("select id from artikli where id = :id");
        query.bindValue(":id", artikal_id);	
        query.exec();
        query.next();
        proizvodID = query.value(0).toString();
	}
}
void QNormativVnes::setFocusLine2()
{
	ui.lineEdit_2->setFocus();
	ui.lineEdit_2->selectAll();

}


void QNormativVnes::on_pushButton_clicked()
{
    CHelperClass hclass(this);
    if (!hclass.isKomintentExists(ui.lineEdit->text()))
    {
        emit scallArtikli((QWidget*)this, ui.lineEdit->text());
		m_bProizvod = true;
    }
    else
    {
        ui.lineEdit_2->setFocus();
    }
}

void QNormativVnes::lineEditPressReturn()
{
	emit scallArtikli((QWidget*)this, ui.lineEdit->text());
}

void QNormativVnes::on_pushButton_2_clicked()
{
    CHelperClass hclass(this);
    if (!hclass.isArtikliExists(ui.lineEdit_2->text()))
    {
        emit scallArtikli((QWidget*)this, ui.lineEdit_2->text());
		m_bProizvod = false;
    }
    else
    {
        ui.lineEdit_4->setFocus();
    }
}

void QNormativVnes::on_pushButton_3_clicked()
{
	CHelperClass hclass(this);
	if (!hclass.isArtikliExists(ui.lineEdit_2->text()))
	{
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Податокот за артикал е невалиден\nОдбери артикал од листата на артикли!"));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		ui.lineEdit_2->setFocus();
		return;
	}


	QLocale loc;
    if(textId.toInt() == -1)
	{
		return;
	}

	//m_id = textId.toInt();

	QString temp = "select id, sifra, artikal, edm from artikli where id =";
	temp += textId;
	QSqlQuery query(temp);
	QString country1 = "";
	QString country2 = "";
	QString country3 = "";
	QString country4 = "";
	while (query.next()) 
	{
		country1 = query.value(query.record().indexOf("id")).toString();
		country2 = query.value(query.record().indexOf("sifra")).toString();
		country3 = query.value(query.record().indexOf("artikal")).toString();
		country4 = query.value(query.record().indexOf("edm")).toString();
		//        ui.lineEdit->setText(country1);
	}

	int row = model->rowCount();

	QStandardItem *item = new QStandardItem(country1);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(0, 50);
	model->setItem(row, 0, item);

	item = new QStandardItem(country2);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(1, 50);
	model->setItem(row, 1, item);

	item = new QStandardItem(country3);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 250);
	model->setItem(row, 2, item);

	item = new QStandardItem(country4);
	item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(2, 250);
	model->setItem(row, 3, item);

	item = new QStandardItem(loc.toString(ui.lineEdit_4->text().toFloat(), 'f', 2));
    item->setTextAlignment(Qt::AlignRight);
    item->setEditable(false);
	ui.tableView->setRowHeight(row, 18);
	ui.tableView->setColumnWidth(6, 80);
	model->setItem(row, 4, item);

	QItemSelectionModel *sm = ui.tableView->selectionModel();
	connect(sm, SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
		this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
	ui.tableView->show();

	ui.lineEdit_2->selectAll();
	ui.lineEdit_3->setText("");
	ui.lineEdit_4->setText("");
	ui.lineEdit_2->setFocus();
	textId = "-1";
}
void QNormativVnes::selectionChanged(QModelIndex modelX,QModelIndex modelY)
{
	selRow = modelX.row();
    editorOpen = false;
    emit closeCell();
}

void QNormativVnes::on_pushButton_6_clicked()
{
	model->removeRow(selRow);
}
void QNormativVnes::pressReturn()
{
    if (ui.pushButton_3->hasFocus())
    {
        on_pushButton_3_clicked();
    }
    else if (ui.pushButton_6->hasFocus())
    {
        on_pushButton_6_clicked();
    }
    else if (ui.tableView->hasFocus())
    {
        if (editorOpen)
        {
            emit closeCell();
        }
        else
        {
            emit editCell();
        }
        editorOpen = !editorOpen;
    }
}

void QNormativVnes::pressF9()
{
	on_pushButton_4_clicked();
}

void QNormativVnes::on_pushButton_4_clicked()
{
	if (!validateProizvod())
	{
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Податокот за артикал е невалиден\nОдбери артикал од листата на артикли!"));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		ui.lineEdit->setFocus();
		return;
	}

	int cols = model->columnCount();
    int rows = model->rowCount();
    if (!rows)
    {
        return;
    }

    int mid=0;
	QSqlDatabase db = QSqlDatabase::database();
	db.transaction();	
	bool sqlStat = true;
	QSqlQuery query;
    for (int i = 0; i < rows; i++)
    {

        QString mTipDok = "P";
        QString mEmpty ="Empty";
        QString mArtikalID = model->item(i, 0)->text();
        QString mArtikalSifra = model->item(i, 1)->text();
        QString mArtikalNaziv = model->item(i, 2)->text();
        QString mArtikalEdm = model->item(i, 3)->text();
        QString mArtikalKolicina = model->item(i, 4)->text();

        query.clear();
        query.prepare(
            "insert into proizvodi_sostav(id_proizvod, id_artikal, kolicina, firma_id) "
            "values(:a1,:a2,:a3,:a4)"
            );

        query.bindValue(":a1", proizvodID);	
        query.bindValue(":a2", mArtikalID);	
        query.bindValue(":a3", mArtikalKolicina);	
        query.bindValue(":a4", 0);	

		sqlStat = sqlStat && query.exec();
		QSqlError err = query.lastError();
	}
	if (sqlStat)
	{
		db.commit();
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Нормативот е успешно внесен."));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
		pressEscape();
	}
	else
	{
		db.rollback();
		QMessageBox msgBox;
		msgBox.setText(trUtf8("Нормативот НЕ Е внесен !!!."));
		msgBox.setStandardButtons(QMessageBox::Ok);
		msgBox.setDefaultButton(QMessageBox::Ok);
		msgBox.exec();
	}
}

void QNormativVnes::on_pushButton_5_clicked()
{
	pressEscape();
}


bool QNormativVnes::existDok(int idDok)
{
    int nCount = 0;
    QString temp = "select count(dok_id) br from dokumenti where dok_tip = 40 and dok_id =";
    temp += QString::number(idDok, 10);
    QSqlQuery query(temp);
    QString country1 = "";
    int fieldNo = query.record().indexOf("br");
    while (query.next()) {
        nCount = query.value(0).toInt() + 1;
    }
    return nCount > 0 ? true : false;
}

bool QNormativVnes::eventFilter(QObject *object, QEvent *event)
{
	if (event->type() == QEvent::FocusIn)
	{
		if (object == ui.lineEdit)
		{
			ui.lineEdit->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_2)
		{
			ui.lineEdit_2->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_3)
		{
			ui.lineEdit_3->setStyleSheet("background-color: yellow");
		}
		if (object == ui.lineEdit_4)
		{
			ui.lineEdit_4->setStyleSheet("background-color: yellow");
		}
        if (object == ui.dateTimeEdit)
        {
            ui.dateTimeEdit->setStyleSheet("background-color: yellow");
        }
	}
	if (event->type() == QEvent::FocusOut)
	{
		if (object == ui.lineEdit)
		{
			ui.lineEdit->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_2)
		{
			ui.lineEdit_2->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_3)
		{
			ui.lineEdit_3->setStyleSheet("background-color: none");
		}
		if (object == ui.lineEdit_4)
		{
			ui.lineEdit_4->setStyleSheet("background-color: none");
		}
        if (object == ui.dateTimeEdit)
        {
            ui.dateTimeEdit->setStyleSheet("background-color: none");
        }

	}

	return false;
}

void QNormativVnes::on_plineEdit3_Pressed()
{
    ui.lineEdit_4->setFocus();
}
void QNormativVnes::on_plineEdit4_Pressed()
{
    on_pushButton_3_clicked();
}
void QNormativVnes::openEditor()
{
    //	tableView->closePersistentEditor(indexPrev);
    QModelIndex index;
    QModelIndexList indexes = ui.tableView->selectionModel()->selection().indexes();
    index = indexes.at(0);	// To get the row/column numbers use 
    if (index.column() > 3)
    {
        ui.tableView->openPersistentEditor(index);
    }
    indexPrev = index;
}

void QNormativVnes::closeEditor()
{
    ui.tableView->closePersistentEditor(indexPrev);
}

bool QNormativVnes::validateProizvod()
{
	bool stat = false;
	CHelperClass hclass(this);
	if (hclass.isArtikliExists(ui.lineEdit->text()))
	{
		stat = true;
	}
	return stat;
}